package topicHandlers;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
//WS is the translation web service
import Logging.Monitor;
import WS.GetResponse;
import WS.Otms;
import WS.OtmsSoap;
import WS.Query;

public class Translate implements MessageListener{
	
	private OtmsSoap translator;
	private String myLang;
	//the received message should be in the form of <username><Seperator><userlang><seperator><message>
	//<seperator>=</sep/>
	public static final String SEPERATOR="</sep/>";
	
	public Translate(String myLang) {
		this.myLang = myLang;
		Otms impl= new Otms();
		this.translator=impl.getOtmsSoap();
	}

	@Override
	public void onMessage(Message message) {
		
		String msg = null;

		try	{
			if (message instanceof TextMessage) {
				msg = ((TextMessage) message).getText();
			}
			else {
				System.out.println("Message of wrong type: "
						+ message.getClass().getName());
				return ;
			}
		} catch (JMSException e) {
			System.out.println("JMSException in onMessage(): " + e.toString());
		} catch (Throwable t) {
			System.out.println("Exception in onMessage():" + t.getMessage());
		}		
		parse(msg);
	}
	
	private String useWS(String fromLang,String inputStr) {
		Query q = new Query();
		q.setSourceLang(fromLang);
		q.setTargetLang(this.myLang);
		q.setMt(1);
		q.setSource(inputStr);
		GetResponse response = translator.otmsGet("mmDemo123", q);
		if (response.isSuccess()) {
			// get the first match
			String translation = response.getMatches().getMatch().get(0).getTranslation();
			return translation;
		} else {
			return "Translation not found";
		}
	}
	
	private void parse(String msg) {
		//get user name
		int endOfUserName=msg.indexOf(SEPERATOR);
		if(endOfUserName==-1) {
			badMessage();
			return;
		}
		String userName=msg.substring(0, endOfUserName);
		msg=msg.substring(endOfUserName+SEPERATOR.length(), msg.length());
		
		//get the message language
		int endOfLang=msg.indexOf(SEPERATOR);
		if (endOfLang==-1) {
			badMessage();
			return;
		}
		String lang=msg.substring(0, endOfLang);
		
		//Translate message if necessary
		msg=msg.substring(endOfLang+SEPERATOR.length(), msg.length());
		String outMessage=null;
		if(lang.equals(this.myLang)) //Message is in own language - no need to translate
			outMessage= msg;
		else
			outMessage=useWS(lang, msg);
		System.out.println("["+userName + ":] "+outMessage+"("+lang+": "+msg+")");
	}
	
	private void badMessage() {
		//maybe add error message to the screen
		Monitor.write(this,"received bad message on topic");
	}
}
